﻿using System.Text.Json;
using Volo.Abp;
using Volo.Abp.DependencyInjection;
using Volo.Abp.ObjectMapping;
using XCWechat.ApiConsts;
using XCWechat.Dtos;
using XCWechat.Helpers;
using XCWechat.Repositories;
using XCWechat.Services.Clients;
using XCWechat.XCAPIs;

namespace XCWechat.Services
{
    [Dependency(ServiceLifetime.Transient)]
    public class AppTokenService : IRemoteService
    {
        public IClientInfoRepository ClientRepository { get; set; }
        public IClientInfoService ClientInfoService { get; set; }
        public IObjectMapper Mapper { get; set; }

        public async Task<string> UpdateAppToken(Guid id)
        {
            ClientInfoDto clientInfo = await ClientRepository.GetClientInfoAsync(id);
            AppTokenUpdateDto appTokenUpdateDto = Mapper.Map<ClientInfoDto, AppTokenUpdateDto>(clientInfo);
            string appToken = await GetAppToken(id);
            appTokenUpdateDto.AppToken = appToken;
            string resultMsg = await ClientInfoService.UpdateAppToken(appTokenUpdateDto);
            return resultMsg;
        }

        private async Task<string> GetAppToken(Guid id)
        {
            ClientInfoDto clientInfo = await ClientRepository.GetClientInfoAsync(id);
            var apiClient = new XCAPIClient(clientInfo.ClientId, clientInfo.ClientSecret);
            var apiRequest = new XCAPIRequest
            {
                Method = HttpMethod.Get,
                Path = PathConst.AppToken
            };
            apiRequest.Params.Add("app_key", clientInfo.AppKey);
            apiRequest.Params.Add("app_signature", SHAHelper.HmacSHA256(clientInfo.AppSecret, clientInfo.AppKey));
            HttpResponseMessage responseMessage = await apiClient.AppTokenExecute(apiRequest);
            string result = responseMessage.Content.ReadAsStringAsync().Result;
            Dictionary<string, object>? dictionary = JsonSerializer.Deserialize<Dictionary<string, object>>(result);
            if (dictionary != null)
            {
                object? data = dictionary.GetValueOrDefault("data");
                if (data != null)
                {
                    string dataStr = Convert.ToString(data);
                    Dictionary<string, object>? dictionary1 = JsonSerializer.Deserialize<Dictionary<string, object>>(dataStr);
                    if (dictionary1 != null)
                    {
                        string appToken = Convert.ToString(dictionary1.GetValueOrDefault("app-token"));
                        return appToken;
                    }
                }
            }
            return "无法获取到正确的app-token";
        }
    }
}
